package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.dto.BatchToMerchantDto;
import com.qiche.dto.VoucherRepositoryDto;
import com.qiche.model.*;
import com.qiche.service.*;
import com.qiche.util.ApplicationUtils;
import com.qiche.util.UserUtils;
import com.qiche.vo.BatchPostCardVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 门店代金券库管理控制器
 * Created by Linzw on 2018/01/24.
 */
@Api(value = "/voucherRepositorys", description = "门店代金券库管理控制器")
@RestController
@RequestMapping("/voucherRepositorys")
public class VoucherRepositoryController {
    @Autowired
    private VoucherRepositoryService repositoryService;
    @Autowired
    private StoreMemberService storeMemberService;
    @Autowired
    private VoucherService voucherService;

    @ApiOperation(value = "根据条件和分页获取门店列表")
    @GetMapping
    public Map<String, Object> getAll(VoucherRepository repository, @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) throws Exception {
        Map<String, Object> map = new HashMap<>();
        User currentUser=UserUtils.getCurrentUser();
        if(currentUser.getMerchantId() == null){
            return null;
        }
        repository.setMerchantId(currentUser.getMerchantId());
        PageInfo<VoucherRepository> pageInfo = repositoryService.selectByPage(repository, page, limit);
        List<VoucherRepositoryDto> dtoList=new ArrayList<>();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        pageInfo.getList().forEach(voucherRepository -> {
            VoucherRepositoryDto dto=new VoucherRepositoryDto();
            dto.setId(voucherRepository.getId());
            dto.setAmount(voucherRepository.getAmount());
            dto.setName(voucherRepository.getName());
            dto.setQuantity(voucherRepository.getQuantity());
            dto.setCreateTime(voucherRepository.getCreateTime());
            if(voucherRepository.getIndefinite()==1){
                dto.setDueTime("长期有效");
            }else {
                dto.setDueTime(simpleDateFormat.format(voucherRepository.getDueTime()));
            }
            dtoList.add(dto);
        });
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", dtoList);
        return map;
    }


    @ApiOperation(value = "根据选中的客户列表批量发券")
    @PostMapping(value = "/batchSend")
    public Result batchSend(@RequestBody BatchPostCardVo batchPostCardVo) {
        Long masterId = batchPostCardVo.getMasterId();
        VoucherRepository repository=repositoryService.selectByKey(masterId);
        List<Integer> customerIdList = batchPostCardVo.getCustomerIdList();
        if (customerIdList.isEmpty()) {
            return Result.createByErrorMessage("找不到需要发送的客户");
        }
        //库存判断
        if(repository.getQuantity()<customerIdList.size()){
            return Result.createByErrorMessage("库存不足");
        }
        boolean isOk = true;
        for (Integer customerId : customerIdList) {
            StoreMember storeMember = storeMemberService.selectByKey(customerId);
            if (storeMember != null) {
                Voucher voucher=new Voucher();
                voucher.setAgentId(repository.getAgentId());
                voucher.setAmount(repository.getAmount());
                voucher.setTitle(repository.getName());
                voucher.setCode(ApplicationUtils.getRandomString(25));
                voucher.setStoreMemberId(storeMember.getId().intValue());
                voucher.setMerchantId(repository.getMerchantId());
                voucher.setIndefinite(repository.getIndefinite());
                voucher.setDueTime(repository.getDueTime());
                voucher.setIsWriteoff(0);
                isOk = voucherService.save(voucher) > 0 && isOk;
                repository.setQuantity(repository.getQuantity()-1);
            }
        }
        //更新库存
        isOk= repositoryService.updateNotNull(repository)> 0 && isOk;
        if (isOk) {
            return Result.createBySuccessMessage("批量发券成功");
        }
        return Result.createByErrorMessage("批量发券失败");
    }

    @ApiOperation(value = "获得抽奖的奖券")
    @GetMapping("/luckyCardAll")
    public Map<String, Object> luckyCardAll() throws Exception {
        Map<String, Object> map = new HashMap<>();
        User currentUser=UserUtils.getCurrentUser();
        if(currentUser.getMerchantId() == null){
            return null;
        }
        VoucherRepository voucherRepository = new VoucherRepository();
        voucherRepository.setMerchantId(currentUser.getMerchantId());
        List<VoucherRepository> pageInfo = repositoryService.selectByMerchantId(currentUser.getMerchantId());
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("data", pageInfo);
        return map;
    }
}
